package com.yc.cloud.filter;


import cn.hutool.core.util.CharsetUtil;
import com.yc.cloud.common.utils.RedisUtil;
import com.yc.cloud.config.LoginCheckConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

import static com.yc.cloud.common.constant.BaseConstant.AUTHORIZATION;
import static com.yc.cloud.common.constant.BaseConstant.TOKEN_LENGTH;
import static com.yc.cloud.common.constant.RedisConstant.SYS_USER_LOGIN;


/**
 * @author 杨智杰
 * @date 2021/7/20 8:50
 */
@Slf4j
@Component
public class LoginCheckFilter implements Filter {

    @Resource
    private LoginCheckConfig config;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 未登录跳转地址
     */
    private static final String NOT_LOGIN = "/notLogin";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding(CharsetUtil.UTF_8);
        if (config.getWhiteListPath().stream().anyMatch(str -> request.getRequestURI().startsWith(str))) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            String token = request.getHeader(AUTHORIZATION);
            if (Objects.isNull(token) || token.length() != TOKEN_LENGTH || !redisUtil.hasKey(SYS_USER_LOGIN + token)) {
                request.getRequestDispatcher(NOT_LOGIN).forward(request, response);
            } else {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    }

}
